﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entity;
using Controller;
using System.Collections;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;
using ListItem = System.Web.UI.WebControls.ListItem;
using System.Web.UI.HtmlControls;
using Table = iTextSharp.text.Table;


namespace Web
{
    public partial class MakeCustomerInvoice : System.Web.UI.Page
    {
        CustomerPOController customerPOController=new CustomerPOController();
        CustomerPOEntity customerPOEntity=new CustomerPOEntity();
        CustomerPOItemController customerPOItemController=new CustomerPOItemController();
        CustomerPOItemEntity customerPOItemEntity= new CustomerPOItemEntity();
        ProductController productController = new ProductController();
        DeliveryEntity deliveryEntity=new DeliveryEntity();
        IList<DeliveryEntity> deliveryEntities=new List<DeliveryEntity>();
        DeliveryController deliveryController=new DeliveryController();
        Helper helper = new Helper();
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                Session["CustomerInvoiceItem"] = null;
                //bind customers
                CustomerController cc = new CustomerController();
                IList<CustomerEntity> customerEntities = cc.finAllCustomers();
                CustomerDropDownList.DataSource = customerEntities;
                CustomerDropDownList.DataTextField = "ShortName";
                CustomerDropDownList.DataValueField = "Id";
                CustomerDropDownList.DataBind();
                
                this.BindPONoDropDownList();
                this.BindPOItemAndRequestedDateDropDownList();

            }
            this.PreRender += new EventHandler(UpdateFlashMessage);
        }

        private void UpdateFlashMessage(object sender, EventArgs e)
        {
            helper.ShowFlashMessage(FlashMessageLabel);
        }

        protected void BindPONoDropDownList()
        {
            int custormerId = Convert.ToInt32(CustomerDropDownList.SelectedValue);

            IList<CustomerPOEntity> customerPoEntities = customerPOController.FindPendingCustomerPOByCustomerId(custormerId);

            if (customerPoEntities.Count > 0)
            {
                PONoDropDownList.DataSource = customerPoEntities;
                PONoDropDownList.DataTextField = "No";
                PONoDropDownList.DataValueField = "Id";
                PONoDropDownList.DataBind();
                
                this.BindPOItemAndRequestedDateDropDownList();
            }
            else
            {
                Session["FlashMessage"] = "Error: No Pending PO From That Customer";
                Session["FlashMessageType"] = "error";
            }
        }
        protected void PONoDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindPOItemAndRequestedDateDropDownList();
        }
        protected void BindPOItemAndRequestedDateDropDownList()
        {
            int customerPOId = Convert.ToInt32(PONoDropDownList.SelectedValue);
            CustomerPOController customerPoController = new CustomerPOController();
            customerPOEntity = customerPoController.findCustomerPOById(customerPOId);
            ShippingAddressLabel.Text = customerPOEntity.Address;
            IList<CustomerPOItemEntity> customerPoItemEntities =
                customerPOItemController.findUncompletedCustomerPOItemsByCustPOId(customerPOId);
            ItemAndRequestedDateDropDownList.DataSource = customerPoItemEntities;
            ItemAndRequestedDateDropDownList.DataTextField = "ProductNameAndRequestedDate";
            ItemAndRequestedDateDropDownList.DataValueField = "Id";
            ItemAndRequestedDateDropDownList.DataBind();
            ItemAndRequestedDateDropDownList.Items.Insert(0, new ListItem("--Select Item--", "0"));
            if (ItemAndRequestedDateDropDownList.SelectedIndex == 0)
            {
                InsertButton.Enabled = false;
            }
        }

        private CustomerPOItemEntity ConstructCustomerPOItemEntity()
        {
            if (ItemAndRequestedDateDropDownList.SelectedIndex != 0)
            {
                int poItemId = Convert.ToInt32(ItemAndRequestedDateDropDownList.SelectedValue);
                CustomerPOItemEntity customerPoItemEntity = customerPOItemController.findCustomerPOItemByCustomerPOItemId(poItemId);
                return customerPoItemEntity;
            }
            else
            {
                return null;
            }

        }


        protected void ItemAndRequestedDateDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ItemAndRequestedDateDropDownList.SelectedIndex != 0)
            {
                CustomerPOItemEntity customerPoItemEntity = this.ConstructCustomerPOItemEntity();
                UnitPriceLabel.Text = customerPoItemEntity.Price.ToString();
                QuantityTextBox.Text = customerPoItemEntity.RequestQty.ToString();
                int productId = customerPoItemEntity.ProductId;
                StockItemController stockItemController = new StockItemController();
                IList<StockItemEntity> batchList = stockItemController.FindBatchNoByProductId(productId);
                BatchNoDropDownList.DataSource = batchList;
                BatchNoDropDownList.DataValueField = "Id";
                BatchNoDropDownList.DataTextField = "BatchNo";
                BatchNoDropDownList.DataBind();
                if (batchList.Count<=0)
                {
                    InsertButton.Enabled = false;
                }
                else
                {
                    InsertButton.Enabled = true;
                }
                

            }
            else
            {
                
                    InsertButton.Enabled = false;
               
            }
           
        }

        private  void ConstructDeliveryEntity()
        {
            deliveryEntity.PoNo = PONoDropDownList.SelectedItem.Text;
            deliveryEntity.Quantity = Convert.ToInt32(QuantityTextBox.Text);
            deliveryEntity.UnitPrice = Convert.ToDecimal(UnitPriceLabel.Text);
            CustomerPOItemEntity customerPoItemEntity = this.ConstructCustomerPOItemEntity();
            deliveryEntity.ProductId = customerPoItemEntity.ProductId;
            deliveryEntity.ProductNo = customerPoItemEntity.ProductNo;
            deliveryEntity.ProductName = customerPoItemEntity.ProductName;
            deliveryEntity.Amount = deliveryEntity.Quantity * deliveryEntity.UnitPrice;
            deliveryEntity.RequestedDate = customerPoItemEntity.RequestDate;
            deliveryEntity.CustPOItemId = customerPoItemEntity.Id;
            deliveryEntity.Revision = customerPoItemEntity.Revision;
            
            deliveryEntity.StockItemId = Convert.ToInt32(BatchNoDropDownList.SelectedValue);
            deliveryEntity.CustId = 1;
            deliveryEntity.BatchNo = BatchNoDropDownList.SelectedItem.Text;
            deliveryEntity.RequestQty = customerPoItemEntity.RequestQty;
            deliveryEntity.Lot = customerPoItemEntity.Lot;
            deliveryEntity.InvoiceNo = InvoiceNoTextBox.Text;
            deliveryEntities.Add(deliveryEntity);
        }

        protected void InsertButton_Click(object sender, EventArgs e)
        {
            if (Session["CustomerInvoiceItem"] == null)
            {
                
               this.ConstructDeliveryEntity();

            }
            else
            {
                deliveryEntities = Session["CustomerInvoiceItem"] as IList<DeliveryEntity>;
                this.ConstructDeliveryEntity();
                

            }
            Session["CustomerInvoiceItem"] = deliveryEntities;
            CustomerInvoiceItemGridView.DataSource = deliveryEntities;
            CustomerInvoiceItemGridView.DataBind();
            CountSubTotal();
            CountTotal();
        }

        protected void ShippingAndInsuranceTextBox_TextChanged(object sender, EventArgs e)
        {
            CountTotal();
        }

        public void CountTotal()
        {
            string pat = @"^[0-9]+(.[0-9]{1,3})?$";

            Regex r = new Regex(pat, RegexOptions.Compiled);
            Match m = r.Match(ShippingAndInsuranceTextBox.Text);
            if (m.Success)
            {
                TotalLabel.Text =
                    (Convert.ToDouble(SubTotalLabel.Text) +
                    Convert.ToDouble(ShippingAndInsuranceTextBox.Text)).ToString();
            }
            if(!m.Success)
            {
                TotalLabel.Text = SubTotalLabel.Text;
            }

        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            try
            {
                int row = CustomerInvoiceItemGridView.Rows.Count;
                if (row > 0)
                {
                    int paid = 0;
                    string stockOutNo = InvoiceNoTextBox.Text;
                    int custId = Convert.ToInt32(CustomerDropDownList.SelectedValue);
                    DateTime date = Convert.ToDateTime(DateTextBox.Text);
                    StockOutController stockOutController = new StockOutController();
                    //add stock out record.
                    int stockOutId = stockOutController.addStockOut(stockOutNo, custId, date);

                    if(stockOutId<=0)
                    {
                        throw new Exception("You Already Add a Invoice With The Same No!");
                    }
                    int custPOId = Convert.ToInt32(PONoDropDownList.SelectedValue);
                    if (PaidCheckBox.Checked)
                    {
                        paid = 1;
                    }
                    CustInvoiceController customerInvoiceController = new CustInvoiceController();
                    //add cust invoice record.
                    customerInvoiceController.addCustInvoice(stockOutNo, stockOutId, paid);

                    IList<DeliveryEntity> deliveryEntities = Session["CustomerInvoiceItem"] as IList<DeliveryEntity>;

                    if(deliveryEntities==null)
                    {
                        throw new Exception("No Items In The List Or You Have Submitted!");
                    }
                    //add delivery records, update product stock, update vendor po item complete qty and status, update cust po status.
                    foreach (DeliveryEntity d in deliveryEntities)
                    {
                        int productId = d.ProductId;
                        int stockItemId = d.StockItemId;
                        int qty = d.Quantity;
                        int custPoItemId = d.CustPOItemId;
                        deliveryController.addDelivery(stockOutId, stockItemId, qty, custPoItemId);
                        productController.updateStock(productId, -qty);
                        StockItemController stockItemController = new StockItemController();
                        stockItemController.UpdateStockItemStock(stockItemId, -qty);
                        customerPOItemEntity = customerPOItemController.findCustomerPOItemByCustomerPOItemId(d.CustPOItemId);
                        int completeQty = customerPOItemController.updateCustPOItem(custPoItemId, qty);
                        if (completeQty >= customerPOItemEntity.RequestQty)
                        {
                            customerPOItemController.updateCustPOItem(custPoItemId, "completed");
                        }
                        if (completeQty < customerPOItemEntity.RequestQty)
                        {
                            customerPOItemController.updateCustPOItem(custPoItemId, "ongoing");
                        }

                    }
                    IList<CustomerPOItemEntity> custPoItemEntities = new List<CustomerPOItemEntity>();
                    custPoItemEntities = customerPOItemController.findCustomerPOItemsByCustPOId(custPOId);
                    int completeCount = 0;

                    foreach (CustomerPOItemEntity custPoItemEntity in custPoItemEntities)
                    {

                        if (custPoItemEntity.Status != "completed")
                        {
                            completeCount++;
                        }

                    }
                    if (completeCount != 0)
                    {
                        customerPOController.updateCustPOStatus(custPOId, "completed");
                    }
                    int ongoingCount = 0;
                    foreach (CustomerPOItemEntity custPoItemEntity in custPoItemEntities)
                    {

                        if (custPoItemEntity.Status != "ongoing")
                        {
                            ongoingCount++;
                        }

                    }
                    if (ongoingCount != 0)
                    {
                        customerPOController.updateCustPOStatus(custPOId, "ongoing");
                    }

                    IList<DeliveryEntity> deliveryEntities1 =
                        Session["CustomerInvoiceItem"] as IList<DeliveryEntity>;
                    Session["PrepareToGeneratePDF"] = deliveryEntities1;

                    Session["CustomerInvoiceItem"] = null;

                    //ClientScript.RegisterStartupScript(this.Page.GetType(), "Success!",
                    //                                   "if(window.confirm('You have add customer invoice successfully! Go back and refresh page?')){window.location.href='CustomerInvoice.aspx';}",
                    //                                   true);
                    //SuccessfulLabel.Text = "You have add customer invoice successfully!";
                    Session["FlashMessage"] = "Success: Add Customer Invoice Successfully!";
                    Session["FlashMessageType"] = "success";
                }
                else
                {
                    //ClientScript.RegisterStartupScript(this.Page.GetType(), "No insert!", "alert('Please insert item(s).')", true);
                    //SuccessfulLabel.Text = "Please insert item(s).";
                    Session["FlashMessage"] = "Error: Please Insert Item(s).!";
                    Session["FlashMessageType"] = "error";
                }
            }
            catch (Exception ex)
            {
                Session["FlashMessage"] = "Error: "+ex.Message;
                Session["FlashMessageType"] = "error";
            }
            
        }
        protected void InvoicePDFButton_Click(object sender, EventArgs e)
        {
            CustInvoiceController custInvoiceController = new CustInvoiceController();
            CustomerInvoiceEntity customerInvoiceEntity =
                custInvoiceController.FindCustomerInvoiceByInvoiceNo(InvoiceNoTextBox.Text).First();
            string filename = ExcelGenerator.GenerateExcelForCustomerInvoiceById(customerInvoiceEntity.CustomerInvoiceId);
            Response.Redirect("~/"+filename);
        }

        //Generate Customer Invoice PDF
        protected void InvoicePDFButton_Click_Old(object sender, EventArgs e)
        {
            if (Session["PrepareToGeneratePDF"] != null)
            {
                //Set PDF size
                iTextSharp.text.Rectangle rec = new Rectangle(900,1250); //A4


                //Create PDF
                iTextSharp.text.Document doc = new iTextSharp.text.Document(rec);

                //Create Pdfwriter object for document
                //Create PDF name
                string PDFName = "Invoice" + InvoiceNoTextBox.Text + ".pdf";
                iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
                                                          new System.IO.FileStream(
                                                              Server.MapPath("./") + "PDF/" + PDFName,
                                                              System.IO.FileMode.Create));

                doc.Open();
                //Add an image object
                iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(Server.MapPath("logo.jpg"));
                
                //Add a table
                iTextSharp.text.Table table = new iTextSharp.text.Table(10);
                table.BorderWidth = 0;
                //table.BorderColor = new Color(0, 0, 0);
                table.Padding = 5;
                table.Spacing = 5;

                Cell logo = new Cell(jpeg);
                //logo.Header = true;
                logo.Colspan = 10;
                logo.Border = 1;
                logo.BorderColorBottom = new Color(0x00, 0x00, 0x00);
                logo.BorderColorLeft = new Color(0xFF, 0xFF, 0xFF);
                logo.BorderColorRight = new Color(0xFF, 0xFF, 0xFF);
                logo.BorderColorTop = new Color(0xFF, 0xFF, 0xFF);
                logo.HorizontalAlignment = 1;
                
                table.AddCell(logo);

                Cell gst = new Cell("Co. & GST Registration Number: 20-0105271-M");
                gst.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
                gst.Border = 0;
                gst.Colspan = 6;
                gst.HorizontalAlignment = 0;
                table.AddCell(gst);

                //Create a phrase that contain font style
                Phrase myPhrase = new Phrase("TAX INVOICE", FontFactory.GetFont(FontFactory.TIMES_BOLD, 14, Font.BOLD));
                Cell title = new Cell(myPhrase);
                title.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
                title.Border = 0;
                title.Colspan = 4;
                title.HorizontalAlignment = 1;
                table.AddCell(title);

                Phrase customerPhrase = new Phrase("Customer", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, Font.BOLD));
                Cell customer = new Cell(customerPhrase);
                customer.Colspan = 6;
                customer.HorizontalAlignment = 0;
                customer.Border = 0;
                table.AddCell(customer);


                Cell invoiceInfo = new Cell();
                string invoiceNo = this.InvoiceNoTextBox.Text;
                string date = this.DateTextBox.Text;
                Paragraph i1 = new Paragraph("Invoice No.: " + invoiceNo);
                Paragraph i2 = new Paragraph("Date: " + date);
                Paragraph i3 = new Paragraph("Yr PO No.: -");
                Paragraph i4 = new Paragraph("Terms: WIRE-TRANSFER");
                Paragraph i5 = new Paragraph("Currency: USD");
                invoiceInfo.Add(i1);
                invoiceInfo.Add(i2);
                invoiceInfo.Add(i3);
                invoiceInfo.Add(i4);
                invoiceInfo.Add(i5);
                invoiceInfo.Colspan = 4;
                invoiceInfo.Rowspan = 6;
                table.AddCell(invoiceInfo);

                Cell customerInfo = new Cell();
                Paragraph p1 = new Paragraph("Company:   SONNAX INDUSTRIES, INC.");
                Paragraph p2 = new Paragraph("Address:   P.O. BOX 440 AUTOMATIC DRIVE");
                Paragraph p3 = new Paragraph("City:      BELLLOWS FALLS");
                Paragraph p4 = new Paragraph("State:     VT ZIP: 05101-0440");
                Paragraph p5 = new Paragraph("Attention: Ms. Debra Rocca");
                Paragraph p6 = new Paragraph("Phone:     802-463-9722");
                Paragraph p7 = new Paragraph("Tariff Code: 8481.90.9080");
                customerInfo.Add(p1);
                customerInfo.Add(p2);
                customerInfo.Add(p3);
                customerInfo.Add(p4);
                customerInfo.Add(p5);
                customerInfo.Add(p6);
                customerInfo.Add(p7);
                customerInfo.Colspan = 6;
                customerInfo.Rowspan = 5;

                table.AddCell(customerInfo);

                Cell qty = new Cell("Qty");
                qty.Colspan = 1;
                table.AddCell(qty);
                Cell no = new Cell("No");
                no.Colspan = 2;
                table.AddCell(no);
                Cell name = new Cell("Name");
                name.Colspan = 2;
                table.AddCell(name);
                Cell rev = new Cell("Rev.");
                rev.Colspan = 1;
                table.AddCell(rev);
                Cell price = new Cell("Unit Price");
                price.Colspan = 2;
                table.AddCell(price);
                Cell total = new Cell("TOTAL");
                total.Colspan = 2;
                table.AddCell(total);
                foreach (GridViewRow r in CustomerInvoiceItemGridView.Rows)
                {

                    string gvNo = r.Cells[0].Text;
                    //string gvName = r.Cells[1].Text;
                    string gvName = customerPOItemController.FindItemCategoryByItemNo(gvNo);
                    string gvQty = ((TextBox)r.Cells[3].FindControl("qtyTextBox")).Text;
                    string gvRev = r.Cells[2].Text;
                    string gvPrice = ((TextBox)r.Cells[4].FindControl("unitPriceTextBox")).Text;
                    string gvTotal = (Convert.ToInt32(gvQty)*Convert.ToDecimal(gvPrice)).ToString();
                    Cell qty1 = new Cell(gvQty);
                    qty1.Colspan = 1;
                    table.AddCell(qty1);
                    Cell no1 = new Cell(gvNo);
                    no1.Colspan = 2;
                    table.AddCell(no1);
                    Cell name1 = new Cell(gvName);
                    name1.Colspan = 2;
                    table.AddCell(name1);
                    Cell rev1 = new Cell(gvRev);
                    rev1.Colspan = 1;
                    table.AddCell(rev1);
                    Cell price1 = new Cell("$" + gvPrice);
                    price1.Colspan = 2;
                    table.AddCell(price1);
                    Cell total1 = new Cell("$" + gvTotal);
                    total1.Colspan = 2;
                    table.AddCell(total1);

                }

                Cell shippingAddress = new Cell();
                shippingAddress.Colspan = 5;
                shippingAddress.Rowspan = 3;
                Paragraph sa = new Paragraph("Shipping Address");
                Paragraph asabove = new Paragraph("AS ABOVE");
                Paragraph country = new Paragraph("Country of Origin: Singapore");
                shippingAddress.Add(sa);
                shippingAddress.Add(asabove);
                shippingAddress.Add(country);
                table.AddCell(shippingAddress);

                Cell amountSumary = new Cell();
                amountSumary.Colspan = 5;
                amountSumary.Rowspan = 3;
                amountSumary.HorizontalAlignment = 2;
                string subTotal = "Sub Total: $" + this.SubTotalLabel.Text;
                string sAndI = "Shipping & Insurance: $" + this.ShippingAndInsuranceTextBox.Text;
                string totalAmount = "TOTAL: $" + this.TotalLabel.Text;
                Paragraph pSubTotal = new Paragraph(subTotal);
                Paragraph pSAndI = new Paragraph(sAndI);
                Paragraph pTotalAmount = new Paragraph(totalAmount);
                amountSumary.Add(pSubTotal);
                amountSumary.Add(pSAndI);
                amountSumary.Add(pTotalAmount);
                table.AddCell(amountSumary);

                Cell shippingMode = new Cell();
                shippingMode.Colspan = 5;
                shippingMode.Rowspan = 3;
                string weight = "Shipping Weight: " + this.WeightTextBox.Text;
                Paragraph sm = new Paragraph("Shipping Mode");
                Paragraph pWeight = new Paragraph(weight);
                Paragraph ups = new Paragraph("UPS Freight Collects");
                shippingMode.Add(sm);
                shippingMode.Add(pWeight);
                shippingMode.Add(ups);
                table.AddCell(shippingMode);

                Cell sign = new Cell("Office Use Only");
                sign.Colspan = 5;
                sign.Rowspan = 3;
                table.AddCell(sign);

                Cell footer = new Cell();
                Phrase footerPhrase =
                    new Phrase("11 Kian Teck Avenue Singapore 628899 tel>65-6261-5607 e-mail>mstan@skyfab.com.sg",
                               FontFactory.GetFont(FontFactory.TIMES, 10));
                footer.Add(footerPhrase);
                footer.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
                footer.Colspan = 10;
                footer.HorizontalAlignment = 1;
                footer.Header = true;
                table.AddCell(footer);
                doc.Add(table);
                doc.Close();
                Response.Redirect("PDF/" + PDFName);
            }
            else
            {
                //SubmitFirstLabel.Text = "Please submit customer invoice first!";
                Session["FlashMessage"] = "Error: Please Submit Customer Invoice First!";
                Session["FlashMessageType"] = "error";
            }

        }

        
        //Generate Package PDF
        protected void PackagePDFButton_Click(object sender, EventArgs e)
        {
            if (Session["PrepareToGeneratePDF"] != null)
            {

                iTextSharp.text.Rectangle rec = new Rectangle(900,1250);
               
                iTextSharp.text.Document doc = new iTextSharp.text.Document(rec);

                
                string pdfName = "Package_" + InvoiceNoTextBox.Text+".pdf";
                iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
                                                          new System.IO.FileStream(
                                                              Server.MapPath("./")+"PDF/"+ pdfName,
                                                              System.IO.FileMode.Create));

                doc.Open();


                iTextSharp.text.Table table = new iTextSharp.text.Table(11);
                table.BorderWidth = 1;
                table.BorderColor = new Color(0, 0, 0);
                table.Padding = 5;
                table.Spacing = 5;
                
                Cell customer = new Cell("Customer");
                customer.Colspan = 7;
                customer.HorizontalAlignment = 0;
                table.AddCell(customer);


                Cell deliveryInfo = new Cell();
                string invoiceNo = this.InvoiceNoTextBox.Text;
                string deliveryDate = System.DateTime.Now.ToString("d MMM, yyyy");
                string poNo = this.PONoDropDownList.SelectedItem.Text;
                Paragraph i1 = new Paragraph("Invoice No.: " + invoiceNo);
                Paragraph i2 = new Paragraph("Date: " + deliveryDate);
                Paragraph i3 = new Paragraph("PO No.: " + poNo);

                deliveryInfo.Add(i1);
                deliveryInfo.Add(i2);
                deliveryInfo.Add(i3);
                deliveryInfo.Colspan = 4;
                deliveryInfo.Rowspan = 6;
                table.AddCell(deliveryInfo);

                Cell customerInfo = new Cell();
                Paragraph p1 = new Paragraph("Company:   SONNAX INDUSTRIES, INC.");
                Paragraph p2 = new Paragraph("Address:   P.O. BOX 440 AUTOMATIC DRIVE");
                Paragraph p3 = new Paragraph("City:      BELLLOWS FALLS");
                Paragraph p4 = new Paragraph("State:     VT ZIP: 05101-0440");
                Paragraph p5 = new Paragraph("Attention: Ms. Debra Rocca");
                Paragraph p6 = new Paragraph("Phone:     802-463-9722");
                Paragraph p7 = new Paragraph("Tariff Code: 8481.90.9080");
                customerInfo.Add(p1);
                customerInfo.Add(p2);
                customerInfo.Add(p3);
                customerInfo.Add(p4);
                customerInfo.Add(p5);
                customerInfo.Add(p6);
                customerInfo.Add(p7);
                customerInfo.Colspan = 7;
                customerInfo.Rowspan = 5;

                table.AddCell(customerInfo);

                Cell no = new Cell("No");
                no.Colspan = 2;
                table.AddCell(no);

                Cell name = new Cell("Name");
                name.Colspan = 2;
                table.AddCell(name);

                Cell rev = new Cell("Rev.");
                rev.Colspan = 1;
                table.AddCell(rev);

                Cell batchNo = new Cell("Batch No");
                batchNo.Colspan = 2;
                table.AddCell(batchNo);

                Cell requestQty = new Cell("R-Qty");
                requestQty.Colspan = 1;
                table.AddCell(requestQty);

                Cell deliveryQty = new Cell("D-Qty");
                deliveryQty.Colspan = 1;
                table.AddCell(deliveryQty);

                Cell requestedDate = new Cell("Requested Date");
                requestedDate.Colspan = 2;
                table.AddCell(requestedDate);



                IList<DeliveryEntity> deliveryEntities = Session["PrepareToGeneratePDF"] as IList<DeliveryEntity>;
                foreach (DeliveryEntity deliveryEntity in deliveryEntities)
                {

                    string pkNo = deliveryEntity.ProductNo;
                    string pkName = deliveryEntity.ProductName;
                    int pkRQty = deliveryEntity.Quantity;
                    string pkRev = deliveryEntity.Revision;
                    string pkRequestDate = deliveryEntity.RequestedDate.ToString("d MMM, yyyy");
                    string pkBatchNo = deliveryEntity.BatchNo;
                    int pkDQty = deliveryEntity.Quantity;
                    Cell vno = new Cell(pkNo);
                    vno.Colspan = 2;
                    table.AddCell(vno);

                    Cell vname = new Cell(pkName);
                    vname.Colspan = 2;
                    table.AddCell(vname);

                    Cell vrev = new Cell(pkRev);
                    vrev.Colspan = 1;
                    table.AddCell(vrev);

                    Cell vbatchNo = new Cell(pkBatchNo);
                    vbatchNo.Colspan = 2;
                    table.AddCell(vbatchNo);

                    Cell vrequestQty = new Cell(pkRQty.ToString());
                    vrequestQty.Colspan = 1;
                    table.AddCell(vrequestQty);

                    Cell vdeliveryQty = new Cell(pkDQty.ToString());
                    vdeliveryQty.Colspan = 1;
                    table.AddCell(vdeliveryQty);

                    Cell vrequestedDate = new Cell(pkRequestDate);
                    vrequestedDate.Colspan = 2;
                    table.AddCell(vrequestedDate);

                }

                Cell shippingAddress = new Cell();
                shippingAddress.Colspan = 6;
                shippingAddress.Rowspan = 3;
                Paragraph sa = new Paragraph("Shipping Address");
                Paragraph asabove = new Paragraph("AS ABOVE");
                Paragraph country = new Paragraph("Country of Origin: Singapore");
                shippingAddress.Add(sa);
                shippingAddress.Add(asabove);
                shippingAddress.Add(country);
                table.AddCell(shippingAddress);



                Cell shippingMode = new Cell();
                shippingMode.Colspan = 5;
                shippingMode.Rowspan = 3;
                string weight = "Shipping Weight: " + this.WeightTextBox.Text;
                Paragraph sm = new Paragraph("Shipping Mode");
                Paragraph pWeight = new Paragraph(weight);
                Paragraph ups = new Paragraph("UPS Freight Collects");
                shippingMode.Add(sm);
                shippingMode.Add(pWeight);
                shippingMode.Add(ups);
                table.AddCell(shippingMode);

                Cell footer = new Cell();
                Phrase footerPhrase =
                    new Phrase("11 Kian Teck Avenue Singapore 628899 tel>65-6261-5607 e-mail>mstan@skyfab.com.sg",
                               FontFactory.GetFont(FontFactory.TIMES, 10));
                footer.Add(footerPhrase);
                footer.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
                footer.Colspan = 11;
                footer.HorizontalAlignment = 1;
                footer.Header = true;
                table.AddCell(footer);
                doc.Add(table);
                doc.Close();
                Response.Redirect("PDF/" + pdfName);

            }
            else
            {
                //SubmitFirstLabel.Text = "Please submit customer invoice first!";
                Session["FlashMessage"] = "Error: Please Submit Customer Invoice First!";
                Session["FlashMessageType"] = "error";
            }


        }

        //Genreate Item List PDF
        protected void ItemPDFButton_Click(object sender, EventArgs e)
        {
            if(Session["PrepareToGeneratePDF"]!=null)
            {
                iTextSharp.text.Rectangle rec = new Rectangle(900,1250);
                
                
                iTextSharp.text.Document doc = new iTextSharp.text.Document(rec,1,1,105,45);

                string pdfName = "List_" + InvoiceNoTextBox.Text + ".pdf";
                iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
                                                          new System.IO.FileStream(
                                                              Server.MapPath("./") + "PDF/" + pdfName,
                                                              System.IO.FileMode.Create));

                doc.Open();


                
                IList<DeliveryEntity> deliveryEntities = Session["PrepareToGeneratePDF"] as IList<DeliveryEntity>;

                int count = 0;
                foreach (DeliveryEntity deliveryEntity in deliveryEntities)
                {
                    iTextSharp.text.Table table = new iTextSharp.text.Table(14);
                    table.BorderWidth = 1;
                    table.BorderColor = new Color(0, 0, 0);
                    table.Padding = 1;
                    table.Spacing = 1;
                    
                    
                    string pno = deliveryEntity.ProductNo;
                    int pdeliveryQty = deliveryEntity.Quantity;
                    string poNo = deliveryEntity.PoNo;
                    string invoiceNo = deliveryEntity.InvoiceNo;
                    string batchNo = deliveryEntity.BatchNo;
                    string rev = deliveryEntity.Revision;
                    string rDate = deliveryEntity.RequestedDate.ToString("dd/MMM/yyyy");
                    string sDate = System.DateTime.Now.ToString("dd/MMM/yyyy");
                    int orderQty = deliveryEntity.RequestQty;
                    int lot = deliveryEntity.Lot;
                    string customerFullName = Session["CustomerFullName"].ToString();
                    

                    //*******Line 1******************//
                    Paragraph header1=new Paragraph("SKY FAB SOLUTIONS PTE LTD");
                    header1.Font.IsBold();
                    Paragraph header2=new Paragraph("PACKING SLIP");
                    header2.Font.IsBold();
                    Cell headerCell=new Cell();
                    headerCell.Colspan = 9;
                    headerCell.Add(header1);
                    headerCell.Add(header2);
                    table.AddCell(headerCell);

                    Cell rightPartNoCell=new Cell(pno);
                    rightPartNoCell.Colspan = 3;
                    table.AddCell(rightPartNoCell);

                    Cell rightQtyCell=new Cell(pdeliveryQty.ToString());
                    rightQtyCell.Rowspan = 2;
                    rightQtyCell.Colspan = 2;
                    table.AddCell(rightQtyCell);

                    //*******Line 2******************//
                    Cell toTitleCell=new Cell("TO:");
                    toTitleCell.Colspan = 2;
                    table.AddCell(toTitleCell);

                    Cell toCell=new Cell(customerFullName);
                    toCell.Colspan = 7;
                   
                    table.AddCell(toCell);

                    Cell rightSCOCell=new Cell("SCO-"+batchNo);
                    rightSCOCell.Colspan = 3;
                   
                    table.AddCell(rightSCOCell);

                    //*******Line 3******************//

                    Cell partNoTitleCell=new Cell("PART NO:");
                    
                    partNoTitleCell.Colspan = 2;
                    table.AddCell(partNoTitleCell);

                    Cell partNoCell = new Cell(pno);
                    partNoCell.Colspan = 3;
                    table.AddCell(partNoCell);

                    Cell revTitleCell=new Cell("REV:");
                    revTitleCell.Colspan = 2;
                    table.AddCell(revTitleCell);

                    Cell revCell=new Cell(rev);
                    revCell.Colspan = 2;
                    table.AddCell(revCell);

                    Cell rightBlankCell=new Cell();
                   
                    rightBlankCell.Colspan = 5;
                    rightBlankCell.Rowspan = 6;
                    
                    table.AddCell(rightBlankCell);

                    //*******Line 4******************//
                    Cell PONoTitleCell=new Cell("PO NO:");
                    PONoTitleCell.Colspan = 2;
                    table.AddCell(PONoTitleCell);

                    Cell PONoCell=new Cell(poNo);
                    PONoCell.Colspan = 3;
                    table.AddCell(PONoCell);

                    Cell DueDateTitleCell=new Cell("DUE DATE:");
                    DueDateTitleCell.Colspan = 2;
                    table.AddCell(DueDateTitleCell);

                    Cell DueDateCell=new Cell(rDate);
                    DueDateCell.Colspan = 2;
                    table.AddCell(DueDateCell);

                   

                    //*******Line 5******************//
                    Cell invoiceNoTitleCell=new Cell("INV NO:");
                    invoiceNoTitleCell.Colspan = 2;
                    table.AddCell(invoiceNoTitleCell);

                    Cell invoiceNoCell=new Cell(invoiceNo);
                    invoiceNoCell.Colspan = 3;
                    table.AddCell(invoiceNoCell);

                    Cell shipDateTitleCell=new Cell("SHIP DATE:");
                    shipDateTitleCell.Colspan = 2;
                    table.AddCell(shipDateTitleCell);

                    Cell shipDateCell=new Cell(sDate);
                    shipDateCell.Colspan = 2;
                    table.AddCell(shipDateCell);

                    

                    //*******Line 6******************//
                    Cell batchNoTitleCell=new Cell("JOB NO:");
                    batchNoTitleCell.Colspan = 2;
                    table.AddCell(batchNoTitleCell);

                    Cell batchNoCell=new Cell("SCO- "+batchNo);
                    batchNoCell.Colspan = 3;
                    table.AddCell(batchNoCell);

                    Cell lotTitleCell=new Cell("LOT QTY:");
                    lotTitleCell.Colspan = 2;
                    table.AddCell(lotTitleCell);

                    Cell lotCell=new Cell(lot+" pcs");
                    lotCell.Colspan = 2;
                    table.AddCell(lotCell);

                    

                    //*******Line 7******************//

                    Cell rQTYTitleCell=new Cell("ORDER QTY:");
                    rQTYTitleCell.Colspan = 2;
                    table.AddCell(rQTYTitleCell);

                    Cell rQTYCell = new Cell(orderQty.ToString()+" PCS");
                    rQTYCell.Colspan = 3;
                    table.AddCell(rQTYCell);

                    Cell totalQTYTitleCell=new Cell("TOTAL QTY:");
                    totalQTYTitleCell.Colspan = 2;
                    table.AddCell(totalQTYTitleCell);

                    Cell totalQTYCell = new Cell(pdeliveryQty.ToString()+" pcs");
                    totalQTYCell.Colspan = 2;
                    table.AddCell(totalQTYCell);

                    


                    //*******Line 8******************//
                    Cell remarkTitleCell=new Cell("REMARKS:");
                    remarkTitleCell.Colspan = 2;
                   
                    table.AddCell(remarkTitleCell);

                    Cell remarkCell=new Cell();
                   
                    remarkCell.Colspan = 7;
                    table.AddCell(remarkCell);

                    Cell pagebreak=new Cell(" ");
                    pagebreak.Border = 0;
                    pagebreak.Colspan = 14;
                    
                    table.AddCell(pagebreak);

                    doc.Add(table);
                    count++;

                    if(count%5==0)
                    {
                        doc.NewPage();
                    }

                    

                    

                }
                
                doc.Close();
                Response.Redirect("PDF/" + pdfName);

               
            }
            else
            {
                //SubmitFirstLabel.Text = "Please submit customer invoice first!";
                Session["FlashMessage"] = "Error: Please Submit Customer Invoice First!";
                Session["FlashMessageType"] = "error";
            }

        }

        protected void CustomerDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {

            CustomerController cc = new CustomerController();


            int custormerId = Convert.ToInt32(CustomerDropDownList.SelectedValue);

            CustomerEntity customerEntity = cc.FindCustomerByCustomerId(custormerId);



            IList<CustomerPOEntity> customerPoEntities = customerPOController.FindPendingCustomerPOByCustomerId(custormerId);

            if(customerPoEntities.Count>0)
            {
                PONoDropDownList.DataSource = customerPoEntities;
                PONoDropDownList.DataTextField = "No";
                PONoDropDownList.DataValueField = "Id";
                PONoDropDownList.DataBind();
                int customerPOId = Convert.ToInt32(PONoDropDownList.SelectedValue);
                CustomerPOController customerPoController = new CustomerPOController();
                customerPOEntity = customerPoController.findCustomerPOById(customerPOId);
                ShippingAddressLabel.Text = customerPOEntity.Address;
                Session["CustomerFullName"] = customerPOEntity.CustomerFullName;
                IList<CustomerPOItemEntity> customerPoItemEntities =
                    customerPOItemController.findCustomerPOItemsByCustPOId(customerPOId);
                ItemAndRequestedDateDropDownList.DataSource = customerPoItemEntities;
                ItemAndRequestedDateDropDownList.DataTextField = "ProductNameAndRequestedDate";
                ItemAndRequestedDateDropDownList.DataValueField = "Id";
                ItemAndRequestedDateDropDownList.DataBind();
                ItemAndRequestedDateDropDownList.Items.Insert(0, new ListItem("--Select Item--", "0"));
                if (ItemAndRequestedDateDropDownList.SelectedIndex == 0)
                {
                    InsertButton.Enabled = false;
                }
            }
            else
            {
                Session["FlashMessage"] = "Error: No Pending PO From That Customer";
                Session["FlashMessageType"] = "error";
            }
            
        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            int rowIndex = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
            deliveryEntities = Session["CustomerInvoiceItem"] as IList<DeliveryEntity>;
            foreach (GridViewRow r in CustomerInvoiceItemGridView.Rows)
            {
                if (r.RowIndex == rowIndex)
                {
                    if (deliveryEntities != null)
                    {
                        for (int i = 0; i <= deliveryEntities.Count;i++ )
                        {
                            if (i == rowIndex)
                            {
                                deliveryEntities.RemoveAt(i);
                            }
                        }
                    }
                }
            }
            Session["CustomerInvoiceItem"] = deliveryEntities;
            CustomerInvoiceItemGridView.DataSource = Session["CustomerInvoiceItem"] as IList<DeliveryEntity>;
            CustomerInvoiceItemGridView.DataBind();
            CountSubTotal();
        }

        protected void qtyTextBox_TextChanged(object sender, EventArgs e)
        {
            CountSubTotal();
        }

        protected void unitPriceTextBox_TextChanged(object sender, EventArgs e)
        {
            CountSubTotal();
        }

        public void CountSubTotal()
        {
            double subTotal = 0;
            foreach (GridViewRow r in CustomerInvoiceItemGridView.Rows)
            {
                //subTotal = subTotal + Convert.ToDouble(r.Cells[5].Text);
                TextBox qtyTextBox = (TextBox)r.Cells[3].FindControl("qtyTextBox");
                TextBox unitPriceTextBox = (TextBox)r.Cells[4].FindControl("unitPriceTextBox");
                subTotal = subTotal + Convert.ToDouble(qtyTextBox.Text) * Convert.ToDouble(unitPriceTextBox.Text);

            }
            SubTotalLabel.Text = subTotal.ToString();
            CountTotal();
            
        }

    }
}
